package com.ques.controller;

import com.ques.annotations.LoginRequired;
import com.ques.pojo.User;
import com.ques.service.QuestionService;
import com.ques.service.UserService;
import com.ques.utils.BasicMessage;
import com.ques.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zq  2020-01-05
 */
@RestController
@CrossOrigin  // 跨域
@SuppressWarnings("all")
@RequestMapping("/api")
public class UserRestController {
    @Autowired
    private UserService userService;

    @Autowired
    private QuestionService questionService;

    @Value("${spring.signKey:signKey}")
    private String signKey;

    /**
     * 登陆
     * @param user 携带用户名 密码
     * @param code 验证嘛
     * @param request
     * @return
     */

    @PostMapping("/login")
    @LoginRequired(loginSuccess = false)
    public BasicMessage login(@RequestBody User user , HttpServletRequest request) {
        if (StringUtils.isEmpty(user.getCode())) {
            return BasicMessage.fail().putmessage("message", "验证码不能为空");
        }
        if (user == null || StringUtils.isEmpty(user.getUserMail()) || StringUtils.isEmpty(user.getPassword())) {
            return BasicMessage.fail().putmessage("message", "用户信息错误");
        }
        // 校验验证码
        String message = userService.equalCode(user.getUserMail(), user.getCode());
        if (!StringUtils.isEmpty(message)) {
          return   BasicMessage.fail().putmessage("message", message);
        }
        User loginUser = userService.login(user);
        if (loginUser != null) {
//            颁布token
            Map<String, Object> map = new HashMap(2);
            map.put("id", loginUser.getId());
            map.put("username", loginUser.getUserMail());
            // ip 地址
            String remoteAddr = request.getHeader("x-forwarded-for");// 通过nginx转发的客户端ip
            if (StringUtils.isEmpty(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();// 从request中获取ip
                if (StringUtils.isEmpty(remoteAddr)) {
                    remoteAddr = "127.0.0.1";
                }
            }
            System.out.println(signKey);
            String token = JwtUtil.encode(signKey, map, remoteAddr);
            System.out.println(token);
//            存入redis
            // 将token存入redis一份
            userService.addUserToken(token, loginUser.getId());
            loginUser.setPassword("");
            return BasicMessage.success().putmessage("token", token).putmessage("userInfo",loginUser);
        }
        return BasicMessage.fail().putmessage("message", "用户名或密码错误");
    }
    /**
     * 获取用户信息
     * @param id  用户id
     * @return 用户信息
     */
    @PostMapping("/loginout/{userId}")
    public BasicMessage loginOut(@PathVariable String userId) {
        userService.loginOut(userId);
        return BasicMessage.success();
    }

    /**
     * 获取用户信息
     * @param id  用户id
     * @return 用户信息
     */
    @PostMapping("/userInfo/{userId}")
    public BasicMessage userInfo(@PathVariable String userId) {
        User user = userService.getUserInfo(userId);
        return BasicMessage.success().putmessage("userInfo", user);
    }

    /**
     * 获取验证码
     * @param userEmail 用户邮箱
     * @return
     */
    @PostMapping("/code/{userMail}")
    public BasicMessage sendCode(@PathVariable String userMail) {
        if (StringUtils.isEmpty(userMail)){
            return BasicMessage.fail().putmessage("message", "邮箱不能为空");
        }
        String message = userService.sendCode(userMail);
        // 如果为空  表示发送成功
        if (StringUtils.isEmpty(message)) {
            return BasicMessage.success().putmessage("message", "验证码发送成功");
        }
        return BasicMessage.fail().putmessage("message", message);
    }

    /**
     * 获取所有用户信息
     */
    @PostMapping("/getAllUser/{userId}")
    public BasicMessage getAllUser(@PathVariable String userId){
    // 权限  必须是超级管理员

       return BasicMessage.success().putmessage("message", "");
    }
}

